<template>
  <div class="image-upload">
    <el-upload
      action="#"
      list-type="picture-card"
      :http-request="uploadFn"
      :file-list="fileList"
      :limit="1"
      :class="{ disable: fileList.length > 0 }"
      :on-remove="removeFn"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 上传进度条 -->
    <el-progress v-if="percentShow" :text-inside="true" :stroke-width="18" :percentage="percent" status="success" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// 初始化cos对象
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDHPOAmNo12qRn25wb2FF0Xkv3zrZ3HH5i',
  SecretKey: 'WrxpdJ7tkPuCJE0gOyNaYLzUlrlaFg9S'
})
export default {
  data() {
    return {
      fileList: [],
      percent: 0,
      percentShow: false
    }
  },
  methods: {
    // 删除头像
    removeFn() {
      this.fileList = []
    },
    // 上传头像
    uploadFn(file) {
      this.fileList.push({
        url: ''
      })
      this.percentShow = true
      cos.putObject({
        Bucket: 'hr-project-1312552009', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: (Date.now()).toString(), /* 必须  设置请求地址的名字为时间戳 这样保证不同名*/
        StorageClass: 'STANDARD',
        Body: file.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (err) { return this.$message.fail('发生错误，请重新上传') }
        // this.fileList.push({
        //   url: 'http://' + data.Location
        // })
        this.fileList[0].url = 'http://' + data.Location
        const timer = setTimeout(() => {
          this.percentShow = false
          clearTimeout(timer)
        }, 1000)
      })
    }
  }
}
</script>

<style lang="scss">
.disable {
    .el-upload--picture-card {
        display: none;
    }
}

.image-upload {
    display: inline-block;

    .el-progress {
        width: 100%;
    }
}
</style>
